import { Form, Input, Modal, notification } from 'antd';

import { usePost } from '@/api';

interface CategoryAddProps extends HTMLElementProps {
  type: 'add' | 'edit';
  params?: { categoryId: number };
  refresh: (flow: { id?: number }) => void;
}

export interface FlowModifyFormRef {
  setVisible: (visible: boolean) => void;
  setFormValue: (data: { name: string; icon: string; categoryId: number }) => void;
}

export const FlowModifyForm = memo(
  forwardRef<FlowModifyFormRef, CategoryAddProps>((props, ref) => {
    const [visible, setVisible] = useState(false);
    const [form] = Form.useForm();
    const { loading: addLoading, runAsync: flowAdd } = usePost('/flow/add', {}, { manual: true });
    const loading = addLoading;

    const submit = () => {
      form.validateFields().then((values) => {
        flowAdd({
          ...values,
          ...(props.params || {})
        } as never).then((res) => {
          setVisible(false);
          notification.success({ message: '操作成功' });
          props.refresh({ id: res.id });
          form.resetFields();
        });
      });
    };

    const setFormValue: FlowModifyFormRef['setFormValue'] = (data) => {
      form.setFieldsValue(data);
    };

    // useEffect(() => {
    //   if (!addVisible) return;
    //   form?.setFieldsValue({ flowName: props.flowName, flowDesc: props.flowDesc });
    //   // eslint-disable-next-line react-hooks/exhaustive-deps
    // }, [props.flowName, props.flowDesc, addVisible]);

    useImperativeHandle(ref, () => ({
      setVisible,
      setFormValue
    }));

    return (
      <>
        {props.children && (
          <div className="flow-modify-form" onClick={(e) => {
            setVisible(true);
            e.stopPropagation();
          }}>
            {props.children}
          </div>
        )}

        <Modal
          title={props.type === 'add' ? '新增决策' : '编辑决策'}
          open={visible}
          onOk={submit}
          destroyOnClose
          confirmLoading={loading}
          onCancel={() => setVisible(false)}>
          <Form form={form}>
            <Form.Item label="决策名称" name="flowName" rules={[{ required: true }]}>
              <Input maxLength={20} />
            </Form.Item>
            <Form.Item label="决策说明" name="flowDesc" rules={[{ required: true }]}>
              <Input.TextArea />
            </Form.Item>
          </Form>
        </Modal>
      </>
    );
  })
);
